const QQMapWX = require('qqmap-wx-jssdk.min.js');
const qqmapsdk = new QQMapWX({
  key: 'FQABZ-RETKP-324D7-LWHOJ-4UIVJ-PPF7I' // 必填
});
var appInstance = getApp().globalData;

// 获取当前城市作为location的初始数据.
var getSingleCity = new Promise(function (resolve, reject){
  wx.getLocation({
    type: 'gcj02',
    success(res, data) {
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: res.latitude,
          longitude: res.longitude
        },
        success: function (mapres) { //成功后的回调
          appInstance.jobList = mapres.result.formatted_addresses.recommend;
          appInstance.lat = mapres.result.location.lat;
          appInstance.lng = mapres.result.location.lng;
          resolve({
            fullname: mapres.result.address_component.city.slice(0, mapres.result.address_component.city.length - 1),
            lat: mapres.result.location.lat,
            lng: mapres.result.location.lng,
            citycode: mapres.result.ad_info.city_code.substring(3)
          })
        },
        fail: function (error) {
          console.error(error);
        }
      });
    }
  })
})

// 获取城市的区域
var getCityArea = function(id){
  return new Promise((resolve, reject) => {
    qqmapsdk.getDistrictByCityId({
      // 传入对应省份ID获得城市数据，传入城市ID获得区县数据,依次类推
      id: id, //对应接口是外部传入的id参数。
      success: function (res) {//成功后的回调
        // {
        //   "job": "建邺",
        //     "isCheck": false,
        //       "type": "area"
        // }
        var cityArea = [];
        for (let i of res.result[0]) {
          let item = {
            "job": i.fullname.substring(0, i.fullname.length-1),
            "isCheck": false,
            "type": "area",
            "workTypeId": i.fullname.substring(0, i.fullname.length - 1)
          }
          cityArea.push(item)
        }
        resolve(cityArea)
      },
      fail: function (error) {
        console.error(error);
      }
    });
  })
}

// 获取当前点到目标地的距离
var getDistance = function (dest){
  return new Promise((resolve, reject) => {
    qqmapsdk.calculateDistance({
      from: '',
      to: dest,
      success: function (res) {
        resolve(res.result.elements[0].distance)
      }
    })
  })
  
}

module.exports = {
  getSingleCity: getSingleCity,
  getCityArea: getCityArea,
  getDistance: getDistance
}